<?php

use Drupal\shusy_store\Entity\ShusyStore;

function shusy_store_shusy_store_entity_form($form, &$form_state, ShusyStore $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_store') . '/shusy_store.forms.inc';
  $form_state[ShusyStore::class] = $e;
  $form['user'] = [
    '#type' => 'fieldset',
    '#title' => t('申请人信息'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  ];
  $form['user']['sex'] = [
    '#type' => 'select',
    '#title' => t('性别'),
    '#options' => $e->getSexOptions(),
    '#default_value' => $e->sex,
    '#chosen' => TRUE,
  ];
  $form['user']['name'] = [
    '#type' => 'textfield',
    '#title' => t('姓名'),
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#default_value' => $e->name,
  ];
  $form['user']['phone'] = [
    '#type' => 'textfield',
    '#title' => t('联系电话'),
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#default_value' => $e->phone,
  ];
  $form['user']['identity'] = [
    '#type' => 'textfield',
    '#title' => t('身份证号'),
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#default_value' => $e->identity,
  ];
  $form['user']['level_1'] = [
    '#type' => 'textfield',
    '#title' => t('直推一级'),
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#default_value' => $e->level_1,
  ];
  $form['user']['level_2'] = [
    '#type' => 'textfield',
    '#title' => t('间推二级'),
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#default_value' => $e->level_2,
  ];
  $form['user']['identity_face'] = [
    '#title' => t('身份证正面照'),
    '#type' => 'managed_file',
    '#default_value' => $e->identity_face,
    '#upload_location' => 'public://tmp/',
    '#required' => TRUE,
  ];

  $longitude = NULL;
  $latitude = NULL;
  $longitude = $e->getLongitude();
  $latitude = $e->getLatitude();

  $form['store'] = [
    '#type' => 'fieldset',
    '#title' => t('店铺信息'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  ];
  $form['store']['type'] = [
    '#type' => 'select',
    '#title' => t('店铺类型'),
    '#options' => $e->getTypeOptions(),
    '#required' => TRUE,
    '#default_value' => $e->type,
  ];
  $form['store']['city_id'] = [
    '#type' => 'select',
    '#title' => t('所在城市'),
    '#options' => shusy_city_options(),
    '#required' => TRUE,
    '#default_value' => $e->city_id,
  ];
  $form['store']['logo'] = [
    '#title' => t('店铺LOGO'),
    '#type' => 'managed_file',
    '#default_value' => $e->logo,
    '#upload_location' => 'public://tmp/',
    '#required' => TRUE,
  ];
  $form['store']['business'] = [
    '#title' => t('营业执照'),
    '#type' => 'managed_file',
    '#default_value' => $e->business,
    '#upload_location' => 'public://tmp/',
    '#required' => TRUE,
  ];
  $form['store']['store_name'] = [
    '#type' => 'textfield',
    '#title' => t('店名'),
    '#size' => 60,
    '#maxlength' => 32,
    '#required' => TRUE,
    '#default_value' => $e->store_name,
  ];
  $form['store']['charge'] = [
    '#type' => 'textfield',
    '#title' => t('商家提现手续费比例'),
    '#size' => 16,
    '#required' => TRUE,
    '#default_value' => $e->charge,
    '#element_validate' => ['element_validate_number'],
    '#description' => t('小数 0.1 表示 100元 手续费10元'),
  ];
  $form['store']['store_address'] = [
    '#type' => 'textfield',
    '#title' => t('店铺地址'),
    '#maxlength' => 255,
    '#required' => TRUE,
    '#default_value' => $e->store_address,
  ];
  $form['store']['bank_no'] = [
    '#type' => 'textfield',
    '#title' => t('收款卡号'),
    '#maxlength' => 32,
    '#required' => TRUE,
    '#default_value' => $e->bank_no,
  ];
  $form['store']['bank_name'] = [
    '#type' => 'textfield',
    '#title' => t('开户行'),
    '#maxlength' => 32,
    '#required' => TRUE,
    '#default_value' => $e->bank_name,
  ];
  $form['store']['bank_file'] = [
    '#title' => t('银行卡正面'),
    '#type' => 'managed_file',
    '#default_value' => $e->bank_file,
    '#upload_location' => 'public://tmp/',
    '#required' => TRUE,
  ];
  $form['store']['food_trade_license'] = [
    '#title' => t('食品经营许可证'),
    '#type' => 'managed_file',
    '#default_value' => $e->food_trade_license,
    '#upload_location' => 'public://tmp/',
  ];

  $form['store']['basic_map'] = [
    '#type' => 'fieldset',
    '#title' => t('地图信息'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#prefix' => '<div id="map">',
    '#suffix' => '</div>',
  ];
  $form['store']['basic_map']['search_address'] = [
    '#type' => 'textfield',
    '#title' => t('检索地址'),
    '#size' => 60,
    '#maxlength' => 128,
    '#description' => t('方便在地图中快速标记点.'),
  ];
  $form['store']['basic_map']['search_address']['searchResultPanel'] = [
    '#type' => 'item',
    '#markup' => '<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto;display: none;"></div>',
  ];
  $form['store']['basic_map']['container'] = [
    '#type' => 'container',
    '#prefix' => '<div id="container" class="map container">',
    '#suffix' => '</div>',
  ];
  $form['store']['basic_map']['coordinate'] = [
    '#type' => 'hidden',
    '#default_value' => $e->coordinate,
  ];
  $form['store']['basic_map']['lng'] = [
    '#type' => 'hidden',
    '#default_value' => $longitude,
  ];
  $form['store']['basic_map']['lat'] = [
    '#type' => 'hidden',
    '#default_value' => $latitude,
  ];

  $form['#attached']['js'][] = 'https://api.map.baidu.com/api?v=3.0&ak=' . variable_get_value('store_baidu_ak');
  $form['#attached']['js'][] = drupal_get_path('module', 'shusy_store') . '/js/shusy_store.js';
  $form['#attached']['css'][] = drupal_get_path('module', 'shusy_store') . '/css/shusy_store.css';
  $settings = [
    'lng' => $longitude,
    'lat' => $latitude,
  ];
  $form['#attached']['js'][] = [
    'data' => ['shusyStoreEntityForm' => $settings],
    'type' => 'setting',
  ];
  $form['status'] = [
    '#type' => 'select',
    '#title' => t('状态'),
    '#options' => $e->getStatusOptions(),
    '#default_value' => $e->status,
    '#chosen' => TRUE,
  ];


  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

function shusy_store_shusy_store_entity_form_submit($form, &$form_state) {
  $e = $form_state[ShusyStore::class];
  if ($e instanceof ShusyStore) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $longitude = $form_state['values']['lng'];
    $latitude = $form_state['values']['lat'];

    $e->longitude = $longitude;
    $e->latitude = $latitude;

    if ($e->coordinate == 5) {
      $ak = variable_get_value('store_baidu_ak_web');
      $sk = variable_get_value('store_baidu_sk_web');
      $uri = '/geoconv/v1/';
      $querystring_arrays = [
        'coords' => "{$longitude},{$latitude}",
        'ak' => $ak,
        'from' => 5,
        'to' => 3,
        'output' => 'json',
      ];
      $querystring = http_build_query($querystring_arrays);
      $sn = md5(urlencode($uri . '?' . $querystring . $sk));
      $url = "https://api.map.baidu.com{$uri}?{$querystring}&sn={$sn}";
      $result = drupal_http_request($url);
      if ($result->code == 200) {
        $data = $result->data;
        $data = drupal_json_decode($data);
        $bzb = $data['result'];
        $bzb = reset($bzb);
        $longitude = $bzb['x'];
        $latitude = $bzb['y'];
        $e->coordinate = 3;
        $e->longitude = $longitude;
        $e->latitude = $latitude;
      }
    }

    $e->save();

    $fids = [
      'logo',
      'business',
      'bank_file',
      'identity_face',
      'food_trade_license',
    ];
    foreach ($fids as $str) {
      $fid = $e->{$str};
      if (!empty($fid)) {
        $dir = "public://shusy_store/" . format_date(REQUEST_TIME, 'custom', 'Y/m/d/') . drupal_random_key();
        $result = file_prepare_directory($dir);
        if (empty($result)) {
          drupal_mkdir($dir, 0777, TRUE);
        }
        $file = file_load($fid);
        if (!empty($file)) {
          $file->status = 1;
          file_save($file);
          $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
          $file = file_move($file, "{$dir}/{$fid}.{$ext}");
          file_usage_add($file, 'shusy_store', $str, $file->fid);
        }
      }
    }

  }
}

function shusy_store_shusy_store_delete_form($form, &$form_state, ShusyStore $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_store') . '/shusy_store.forms.inc';
  $form_state[ShusyStore::class] = $e;
  return confirm_form($form,
    t('Are you sure you want to delete %title?', ['%title' => $e->label()]),
    'admin/content/shusy_store/' . $e->id,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

function shusy_store_shusy_store_delete_form_submit($form, &$form_state) {
  $e = $form_state[ShusyStore::class];
  if ($e instanceof ShusyStore) {
    $e->delete();
  }
}

